import time
from Simplified_code.utils.util import *
import os
from multiprocessing import Pool
from Simplified_code.fp_obj import *

def get_haar_image(fname):
    p = dict_json['fingerprint']
    print(p)
    min_fp_length = get_min_fp_length(dict_json)
    # print('min_fp_length',min_fp_length)    # 12.4
    ntimes = get_ntimes(dict_json)
    sample_haar_images = []
    # 读取出csv中数据，同时返回持续时间
    csv_path = dict_json['data']['folder']+fname
    data_list,duration,start_time,end_time = read_csv(csv_path)
    print('样例数据持续时间',duration)
    # print(p['mad_sampling_rate'])  # 1

    # 不采样
    if (p['mad_sampling_rate'] == 1):
            if duration <= min_fp_length:
                print('continue')
                return None

            # 标准化后的向量
            haar_images, nWindows, idx1, idx2, Sxx, t = fp_feature.data_to_haar_images(data_list)
            sample_haar_images.append(haar_images)



    # 采样求mad
    else:
        print('采样求mad暂时未实现')

    if (len(sample_haar_images)):
        total_haar_images = np.concatenate(sample_haar_images, axis=0)
        # np.save('../out/mad/mad_sample.npy', total_haar_images)
        np.save(mad_folder+'%s_sample.npy'%fname,total_haar_images)
    else:
        print("WARNING: File ", fname, " NOT SAMPLED FOR MAD CALCULATION")


def get_haar_stats():
    ntimes = get_ntimes(dict_json)
    print(ntimes)
    sample_haar_images = np.zeros([0, dict_json['fingerprint']['nfreq'] * ntimes])
    print(sample_haar_images)
    files = dict_json['data']['MAD_sample_files']
    print('len(files)',len(files))
    pool = Pool(min(dict_json['performance']['num_fp_thread'], len(files)))
    pool.map(get_haar_image, files)
    sample_haar_images = []
    for file in files:
        file_name = mad_folder+'%s_sample.npy'%file
        if os.path.isfile(file_name):
            partial = np.load(file_name)
            sample_haar_images.append(partial)
            os.remove(file_name)
        else:
            print ("WARNING: File not included in MAD SAMPLE", file_name)

    total_haar_images = np.concatenate(sample_haar_images, axis=0)
    return fp_feature.compute_haar_stats(total_haar_images, type='MAD')



if __name__ == '__main__':
    t_start = time.time()
    path = './data/waveformscegun/fp_input_cegun.json'
    dict_json = load_json_file(path)
    # print(dict_json)
    fp_feature = init_feature_extractor(dict_json)
    print(fp_feature.__dict__)
    mad_folder = dict_json['data']['folder'] + 'mad/'
    if not os.path.exists(mad_folder):
        os.makedirs(mad_folder)

    median, mad = get_haar_stats()

    print(median)
    print(len(median))
    print(mad)
    print(len(mad))

    f = open(gen_mad_fname(dict_json),'w')
    for i in range(len(median)):
        f.write('%.16f,%.16f\n'%(median[i],mad[i]))
    f.close()
    t_end = time.time()
    print('计算median和mad用时%.2f' % (t_end - t_start))
